package net.asfun.jvalog.resource;

import java.util.Collection;
import java.util.Date;

import javax.jdo.Query;

import net.asfun.jvalog.common.Jdoer;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Phase;
import net.asfun.jvalog.util.ValueFormater;

public class PhaseDao {
	
	public static Collection<Phase> listAll() {
		Jdoer<Phase> jdp = JdoerFactory.jdoPhase;
		Query q = jdp.prepareQuery();
		q.setOrdering("date descending");
		return jdp.more(q);
	}

	public static Phase getByDate(Date date) {
		String ym = ValueFormater.date2string(date, "yyyyMM");
		Jdoer<Phase> jdp = JdoerFactory.jdoPhase;
		Phase pha = jdp.unique("yearMonth == '" + ym + "'");
		if ( pha == null ) {
			pha = new Phase();
			pha.setYearMonth(ym);
			pha.setDate(date);
			jdp.save(pha);
		}
		return pha;
	}
}
